package com.youan.pangu.core.mvc.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.youan.pangu.base.util.ResponseUtil;
import com.youan.pangu.base.bean.result.SuccessResponse;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * 取消mvc自带的界面跳转
 */
public class NoViewHandlerInterceptor extends HandlerInterceptorAdapter {
    private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        if(null == modelAndView){
            return;
        }
        if(handler instanceof HandlerMethod){
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Class returnType = handlerMethod.getMethod().getReturnType();
            if(returnType.equals(void.class)){
                ResponseUtil.write(response, objectMapper.writeValueAsString(new SuccessResponse("")));
            }else {

                if(modelAndView.getModel().isEmpty()){
                    String result = modelAndView.getViewName();
                    ResponseUtil.write(response, objectMapper.writeValueAsString(new SuccessResponse(result)));
                }else {
                    Map map = modelAndView.getModel();
                    ResponseUtil.write(response, objectMapper.writeValueAsString(new SuccessResponse(map)));
                }
            }

            if(modelAndView != null) {
                modelAndView.clear();
            }
        }
    }
}
